<script lang="ts" setup>
import type { StateType } from './types';

import { Page } from '@vben/common-ui';
import { useAppConfig } from '@vben/hooks';

import {
  Button,
  Card,
  Input,
  message,
  Popover,
  Select,
  Space,
  TabPane,
  Tabs,
} from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { getNavs } from '#/api/admin/navs';
import {
  createSitemap,
  getSetting,
  postSetting,
  pushBaidu,
} from '#/api/portal/setting';
import { generateUniqueCode } from '#/utils';

defineOptions({
  name: 'PortalAdminSetting',
});
const navs = ref();
const { baseURL } = useAppConfig(import.meta.env, import.meta.env.PROD);
const activeKey = ref('1');
const state: StateType = reactive({
  form: {
    basic_settings: {
      is_alt: '0',
      is_innerchain: '0',
      is_watermark: '0',
    },
    watermark_settings: {
      mark_type: 'text',
      mark_img_remote: '',
      mark_txt: '',
      mark_txt_size: '30',
      mark_txt_color: '#ffffff',
      mark_opacity: '70',
      mark_degree: '9',
    },
    baidu_settings: {
      push_website: '',
      baidu_token: '',
      is_push: '0',
    },
    collect_settings: {
      password: '',
      keywords: '',
      thumbnailURL: '',
      isInHeadimg: '0',
    },
    web404_settings: {
      enable: '0',
      nav_id: '',
      title: '',
      intro: '',
      logo: '',
      bgimg: '',
    },
  },
});
const [BasicForm, BasicFormApi] = useVbenForm({
  handleSubmit: onSubmit,
  resetButtonOptions: { show: false },
  actionWrapperClass: 'text-center',
  schema: [
    {
      component: 'Switch',
      defaultValue: '0',
      componentProps: {
        checkedValue: '1',
        unCheckedValue: '0',
        checkedChildren: '是',
        unCheckedChildren: '否',
      },
      dependencies: {
        trigger: (values) => {
          state.form.basic_settings = {
            ...state.form.basic_settings,
            ...values,
          };
        },
        // 随意一个字段改变时，都会触发
        triggerFields: ['is_alt', 'is_innerchain', 'is_watermark'],
      },
      help: '开启后会替换alt为文章标题',
      fieldName: 'is_alt',
      label: '替换ALT',
    },
    {
      component: 'Switch',
      defaultValue: '0',
      componentProps: {
        checkedValue: '1',
        unCheckedValue: '0',
        checkedChildren: '是',
        unCheckedChildren: '否',
      },
      help: '开启后文章内会自动关联内链',
      fieldName: 'is_innerchain',
      label: '自动内链',
    },
    {
      component: 'Switch',
      defaultValue: '0',
      componentProps: {
        checkedValue: '1',
        unCheckedValue: '0',
        checkedChildren: '是',
        unCheckedChildren: '否',
      },
      help: '开启后文章发布会自动添加水印',
      fieldName: 'is_watermark',
      label: '添加水印',
    },
    {
      component: 'Button',
      help: '生成网站的SITEMAP',
      fieldName: 'action',
      label: 'SiteMap',
    },
  ],
});

const [WatermarkForm, WatermarkFormApi] = useVbenForm({
  handleSubmit: onSubmit,
  schema: [
    {
      component: 'RadioGroup',
      defaultValue: '',
      componentProps: {
        optionType: 'button',
        options: [
          { label: '文字', value: 'text' },
          { label: 'img', value: '图片' },
        ],
      },
      dependencies: {
        trigger: (values) => {
          state.form.watermark_settings = {
            ...state.form.watermark_settings,
            ...values,
          };
        },
        // 随意一个字段改变时，都会触发
        triggerFields: [
          'mark_type',
          'mark_img_remote',
          'mark_txt',
          'mark_txt_size',
          'mark_txt_color',
          'mark_opacity',
          'mark_degree',
        ],
      },
      fieldName: 'mark_type',
      label: '水印类型',
    },
    {
      component: 'Upload',
      fieldName: 'mark_img_remote',
      label: '水印图片',
    },
    {
      component: 'Input',
      defaultValue: '',
      componentProps: {
        placeholder: '请输入',
      },
      fieldName: 'mark_txt',
      label: '水印文字',
    },
    {
      component: 'Input',
      defaultValue: 30,
      componentProps: {
        placeholder: '请输入',
      },
      fieldName: 'mark_txt_size',
      label: '字体大小',
    },
    {
      component: 'ColorPicker',
      defaultValue: '#000000',
      fieldName: 'mark_txt_color',
      label: '文字颜色',
    },
    {
      component: 'Input',
      defaultValue: 70,
      componentProps: {
        placeholder: '请输入水印透明度',
      },
      fieldName: 'mark_opacity',
      help: '0为完全透明',
      label: '水印透明度',
    },
    {
      component: 'RadioGroup',
      componentProps: {
        optionType: 'button',
        options: [
          {
            label: '左上角',
            value: 1,
          },
          {
            label: '上居中',
            value: 2,
          },
          {
            label: '右上角',
            value: 3,
          },
          {
            label: '左居中',
            value: 4,
          },
          {
            label: '居中',
            value: 5,
          },
          {
            label: '右居中',
            value: 6,
          },
          {
            label: '左下角',
            value: 7,
          },
          {
            label: '下居中',
            value: 8,
          },
          {
            label: '右下角',
            value: 9,
          },
        ],
        class: 'grid gap-0 grid-cols-3',
      },
      fieldName: 'mark_degree',
      label: '水印位置',
    },
  ],
  resetButtonOptions: { show: false },
  actionWrapperClass: 'text-center',
});

const [BaiduForm, BaiduFormApi] = useVbenForm({
  handleSubmit: onSubmit,
  schema: [
    {
      component: 'Input',
      defaultValue: '',
      dependencies: {
        trigger: (values) => {
          state.form.baidu_settings = {
            ...state.form.baidu_settings,
            ...values,
          };
        },
        // 随意一个字段改变时，都会触发
        triggerFields: ['baidu_token', 'push_website', 'is_push'],
      },
      componentProps: {
        placeholder: '请输入百度token',
      },
      help: '请先去百度平台获取百度token',
      fieldName: 'baidu_token',
      label: '百度TOKEN',
      rules: 'required',
    },
    {
      component: 'Input',
      defaultValue: '',
      componentProps: {
        placeholder: '请输入推送网址',
      },
      help: '需要推送的网址',
      fieldName: 'push_website',
      label: '推送网址',
      rules: 'required',
    },
    {
      component: 'Switch',
      defaultValue: '0',
      componentProps: {
        checkedValue: '1',
        unCheckedValue: '0',
        checkedChildren: '是',
        unCheckedChildren: '否',
      },
      help: '使用此功能必须设置百度token',
      fieldName: 'is_push',
      label: '实时推送',
    },
    {
      component: 'Button',
      help: '将发布的文章全部推送至百度',
      fieldName: 'action',
      label: '立即推送',
    },
  ],
  resetButtonOptions: { show: false },
  actionWrapperClass: 'text-center',
});

const [CollectForm, CollectFormApi] = useVbenForm({
  handleSubmit: onSubmit,
  schema: [
    {
      dependencies: {
        trigger: (values) => {
          state.form.collect_settings = {
            ...state.form.collect_settings,
            ...values,
          };
        },
        // 随意一个字段改变时，都会触发
        triggerFields: ['password', 'keywords', 'thumbnailURL', 'isInHeadimg'],
      },
      component: 'Input',
      help: '用于第三方采集工具访问接口的密码',
      fieldName: 'password',
      label: '入口密码',
      rules: 'required',
    },
    {
      component: 'Textarea',
      defaultValue: '',
      help: '填写你想要替换的关键词用,隔开如：我=你',
      fieldName: 'keywords',
      label: '替换关键词',
    },
    {
      component: 'Input',
      help: '填写采集时写入的缩略图地址，图床链接',
      fieldName: 'thumbnailURL',
      label: '缩略图地址',
    },
    {
      component: 'Switch',
      defaultValue: '0',
      componentProps: {
        checkedValue: '1',
        unCheckedValue: '0',
        checkedChildren: '开启',
        unCheckedChildren: '关闭',
      },
      help: '开启后则会在内容头部插入缩略图',
      fieldName: 'isInHeadimg',
      label: '头部缩略图',
    },
  ],
  resetButtonOptions: { show: false },
  actionWrapperClass: 'text-center',
});

const [Web404Form, Web404FormApi] = useVbenForm({
  handleSubmit: onSubmit,
  schema: [
    {
      component: 'Switch',
      dependencies: {
        trigger: (values) => {
          state.form.web404_settings = {
            ...state.form.web404_settings,
            ...values,
          };
        },
        // 随意一个字段改变时，都会触发
        triggerFields: ['enable', 'nav_id', 'intro', 'logo', 'bgimg'],
      },
      defaultValue: '0',
      componentProps: {
        checkedValue: '1',
        unCheckedValue: '0',
        checkedChildren: '是',
        unCheckedChildren: '否',
      },
      help: '请在非debug模式下开启',
      fieldName: 'enable',
      label: '是否开启',
    },
    {
      component: 'Select',
      defaultValue: '1',
      help: '404页面需要显示的导航',
      fieldName: 'nav_id',
      label: '页面导航',
    },
    {
      component: 'Input',
      defaultValue: '',
      componentProps: {
        placeholder: '请输入页面标题',
      },
      fieldName: 'title',
      label: '页面标题',
    },
    {
      component: 'Textarea',
      defaultValue: '',
      componentProps: {
        placeholder: '请输入页面描述',
      },
      fieldName: 'intro',
      label: '页面描述',
    },
    {
      component: 'Upload',
      defaultValue: '',
      fieldName: 'logo',
      label: '页面logo',
    },
    {
      component: 'Upload',
      defaultValue: '',
      fieldName: 'bgimg',
      label: '背景图片',
    },
  ],
  resetButtonOptions: { show: false },
  actionWrapperClass: 'text-center',
});

async function onSubmit() {
  const { msg } = await postSetting(state.form);
  message.success(msg);
}
const handleGetNavs = async () => {
  const {
    data: { list },
  } = await getNavs();
  navs.value = list;
};
onMounted(async () => {
  const { data } = await getSetting();
  if (data.watermark_settings) {
    data.watermark_settings.mark_opacity = Number(
      data.watermark_settings.mark_opacity,
    );
    data.watermark_settings.mark_degree = Number(
      data.watermark_settings.mark_degree,
    );
    data.watermark_settings.mark_txt_size = Number(
      data.watermark_settings.mark_txt_size,
    );
    WatermarkFormApi.setValues(data.watermark_settings);
    state.form.watermark_settings = {
      ...state.form.watermark_settings,
      ...data.watermark_settings,
    };
  }
  if (data.web404_settings) {
    Web404FormApi.setValues(data.web404_settings);
    state.form.web404_settings = {
      ...state.form.web404_settings,
      ...data.web404_settings,
    };
  }
  if (data.collect_settings) {
    CollectFormApi.setValues(data.collect_settings);
    state.form.collect_settings = {
      ...state.form.collect_settings,
      ...data.collect_settings,
    };
  }
  if (data.basic_settings) {
    BasicFormApi.setValues(data.basic_settings);
    state.form.basic_settings = {
      ...state.form.basic_settings,
      ...data.basic_settings,
    };
  }
  if (data.baidu_settings) {
    BaiduFormApi.setValues(data.baidu_settings);
    state.form.baidu_settings = {
      ...state.form.baidu_settings,
      ...data.baidu_settings,
    };
  }
  await handleGetNavs();
});

const handlePushBaidu = () => {
  BaiduFormApi.validate().then(async ({ valid }) => {
    if (valid) {
      const { msg } = await pushBaidu();
      message.success(msg);
    }
  });
};

const handleCreateSitemap = async () => {
  const { msg } = await createSitemap();
  message.success(msg);
};

// 生成随机密码
const generateRandomPassword = (length: number) => {
  CollectFormApi.setFieldValue('password', generateUniqueCode(length));
};
</script>
<template>
  <Page>
    <Card>
      <Tabs v-model:active-key="activeKey">
        <TabPane key="1" force-render tab="基本设置">
          <BasicForm>
            <template #action="slotProps">
              <Space>
                <Button
                  v-bind="slotProps"
                  type="primary"
                  @click="handleCreateSitemap"
                >
                  生成SiteMap
                </Button>
                <Button
                  :href="`${baseURL}/sitemap.xml`"
                  target="_blank"
                  type="link"
                >
                  XML地址
                </Button>
                <Button
                  :href="`${baseURL}/sitemap.txt`"
                  target="_blank"
                  type="link"
                >
                  TXT地址
                </Button>
              </Space>
            </template>
          </BasicForm>
        </TabPane>
        <TabPane key="2" tab="水印设置">
          <WatermarkForm />
        </TabPane>
        <TabPane key="3" tab="百度推送">
          <BaiduForm>
            <template #action="slotProps">
              <Button
                v-bind="slotProps"
                type="primary"
                @click="handlePushBaidu"
              >
                一键推送
              </Button>
            </template>
          </BaiduForm>
        </TabPane>
        <TabPane key="4" tab="采集设置">
          <CollectForm>
            <template #password="slotProps">
              <Input v-bind="slotProps" style="width: calc(100% - 200px)">
                <template #addonBefore>
                  <Button type="link" @click="generateRandomPassword(16)">
                    随机密码
                  </Button>
                </template>
                <template #addonAfter>
                  <Popover title="使用说明：">
                    <template #content>
                      <div>
                        <p style="color: red">可对接火车头等采集工具</p>
                        <p style="color: red">
                          发布接口地址(POST)：你的网址/api/portal/collect
                        </p>
                        <p style="color: red">
                          获取分类接口地址(GET)：你的网址/api/portal/collect/categories
                        </p>
                      </div>
                    </template>
                    <Button type="link">使用说明</Button>
                  </Popover>
                </template>
              </Input>
            </template>
          </CollectForm>
        </TabPane>
        <TabPane key="5" tab="404设置">
          <Web404Form>
            <template #nav_id="slotProps">
              <Select
                v-bind="slotProps"
                :field-names="{
                  label: 'name',
                  value: 'id',
                  options: 'children',
                }"
                :options="navs"
                style="width: 200px"
              />
            </template>
          </Web404Form>
        </TabPane>
      </Tabs>
    </Card>
  </Page>
</template>

<style lang="scss" scoped></style>
